import re
import time
import json
import simplejson
from api.base import *
from api.folder import *
from common.logger import logger
from common.retcode import RetCode
from common.types import RecInfo
from common.models import FileList

class RecycleAction(FolderAction):
	def __init__(self, sess_wp: SessionWrapper):
		super(RecycleAction, self).__init__(sess_wp)

	def get_rec_file_list(self) -> FileList:
		"""获取回收站文件夹列表"""
		results = FileList()
		page = 1
		data = []
		url = self._host_url + '/v2/listRecycleBin.action'

		while True:
			resp = self._get(url, params={'pageNum': page, 'pageSize': 60})
			if not resp:
				logger.error("Rec file list: network error!")
				return None
			resp = resp.json()
			familyId = resp['familyId']
			data_, done = self._get_more_page(resp)
			data.extend(data_)
			if done:
				break
			page += 1
			time.sleep(0.5)  # 大量请求可能会被限制

		for item in data:
			name = item['fileName']
			id_ = item['fileId']
			pid = item['parentId']
			ctime = item['createTime']
			optime = item['lastOpTime']
			size = item['fileSize']
			ftype = item['fileType']
			durl = item['downloadUrl']
			isFolder = item['isFolder']
			isFamily = item['isFamilyFile']
			path = item['pathStr']
			results.append(RecInfo(name=name, id=id_, pid=pid, ctime=ctime, optime=optime, size=size,
								   ftype=ftype, isFolder=isFolder, durl=durl, isFamily=isFamily, path=path,
								   fid=familyId))
		return results

	def rec_restore(self, file_info):
		"""还原文件"""
		return self._batch_task(file_info, 'RESTORE')

	def rec_delete(self, file_info):
		"""回收站删除文件"""
		url = self._host_url + '/v2/deleteFile.action'
		resp = self._get(
			url, params={'familyId': file_info.fid, 'fileIdList': file_info.id})
		if resp and resp.json()['success']:
			return RetCode.SUCCESS
		else:
			return RetCode.FAILED

	def rec_empty(self, file_info):
		"""清空回收站"""
		url = self._host_url + '/v2/emptyRecycleBin.action'
		resp = self._get(url, params={'familyId': file_info.fid})
		if resp and resp.json()['success']:
			return RetCode.SUCCESS
		else:
			return RetCode.FAILED